package ru.osu.acm.testing.listeners;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * User: Aleksey
 * Date: 03.03.2009
 * Time: 16:35:38
 */
public class SessionTimeoutFilter implements Filter {
    private String timeoutPage = "login.faces";

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            // is session expire control required for this request?
            if (isSessionControlRequiredForThisResource(httpServletRequest)) {
                // is session invalid?
                if (isSessionInvalid(httpServletRequest)) {
                    String timeoutUrl = httpServletRequest.getContextPath() + "/" + getTimeoutPage();

                    System.out.println("Session is invalid or user is not logged in! redirecting to timeoutpage : " + timeoutUrl);

                    httpServletResponse.sendRedirect(timeoutUrl);
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    private boolean isSessionControlRequiredForThisResource(HttpServletRequest httpServletRequest) {
        String requestPath = httpServletRequest.getRequestURI();
        return !requestPath.contains(getTimeoutPage());
    }

    private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
        return (httpServletRequest.getRequestedSessionId() != null) && !httpServletRequest.isRequestedSessionIdValid();
    }

    public void destroy() {
    }

    public String getTimeoutPage() {
        return timeoutPage;
    }

    public void setTimeoutPage(String timeoutPage) {
        this.timeoutPage = timeoutPage;
    }
}
